<template>
  <div>
    <mt-field label="标题" placeholder="请输入名称" v-model="title"></mt-field>
    <mt-switch v-model="hasEndtime">设置截止时间</mt-switch>
    <mt-field label="截止时间" type="date" v-model="endDate" v-if="hasEndtime"></mt-field>
    <mt-switch v-model="hasEnrollLimit">设置人数上限</mt-switch>
    <mt-field label="人数上限" type="number" placeholder="请输入人数上限" v-model="enrollLimit" v-if="hasEnrollLimit"></mt-field>
    <mt-datetime-picker
      ref="picker"
      type="date"
      v-model="pickerValue">
    </mt-datetime-picker>
    <mt-checklist
      title="选择必填字段"
      fields="value"
      v-model="fields"
      :options="options">
    </mt-checklist>

    <mt-button type="primary" class="btn-create" size="large" @click="addEvent()">确定</mt-button>
  </div>
</template>


<script>
  export default {
    data() {
      return {
        title: '',
        endDate: '',
        enrollLimit: 1,
        fields: [1],
        options:[],
        hasEndtime: false,
        hasEnrollLimit: false,
        pickerValue:''
      };
    },
    methods: {
      addEvent(){

        const that = this;
        // 获取 csrf token
        const csrf = this.$cookie.get('csrftoken');
        if (!csrf){
            that.$toast({
              message: '请确认已登录',
            });
            return;
        }
        const newEvent = {
          event: {
            title: that.title,
            endTime: that.endDate===''? '':that.endDate + " 23:59:59",
            enrollLimit: that.hasEnrollLimit? that.enrollLimit : 0 // 默认无人数限制
          },
          fields: that.fields
        };
        const URL = that.$const.ctx + "/api/event/create"
        that.$axios.post(URL, newEvent, 
        {
          headers: {'X-CSRFToken': csrf},
        }).then(resp => {
          if(resp.data.code === 0){
            that.$toast({
              message: '操作成功',
              iconClass: 'icon icon-success'
            });
            //跳转到活动报名
            that.$router.push({path: '/' + resp.data.event.id + '/enroll'});
          } else {
            that.$toast({
              message: '创建失败',
            });
          }
        });

      },
      loadOptions(){
        const that = this;
        const URL = that.$const.ctx + '/api/key'
        that.$axios.get(URL).then(resp => {
          for(let k in resp.data){
            that.options.push({label: resp.data[k].keyNameCn, value: resp.data[k].id});
          }
        });
      },
    },
    created(){
      this.loadOptions();
    },
  };
</script>

<style scoped>
  .btn-create {
    margin-top: 15px;
  }
  .mint-switch {
    background-color: #fff;
    padding: 10px 10px;
  }
</style>
